package wh.ispct

import grails.gorm.DetachedCriteria
import java.text.SimpleDateFormat
import java.text.MessageFormat

/**
 * 文档内容
 * @author zhou
 *
 */
class ContentController {
	
	def show() {
		Content c = Content.get(params.id)
		
		//路径path
		Menu leaf = c.menu
		List<Menu> path = new ArrayList<Menu>()
		while(leaf !=null) {
			path.add(0,leaf)
			leaf = leaf.parentMenu
		}
		c.readCount++
		c.save()
		
		def pre = Content.findAllByMenuAndIdLessThan(c.menu,c.id,[max:1,sort:"id",order:"desc"])
		def next = Content.findAllByMenuAndIdGreaterThan(c.menu,c.id,[max:1,sort:"id",order:"asc"])
		
		render (view:"show",model:["content":c,
			pre: (pre.size() > 0 ? pre[0]: null ),
			next:(next.size() > 0 ? next[0] : null),"path":path])
	}
	
	def search(){
		//显示列表
		def max =  20
		def offset = 0
		if(params.max) 
			max = params.max.toInteger()
		if(params.offset) 
			offset = params.offset.toInteger()
		Menu m = Menu.get(params.menuId)
		//查询条件
		def hql = "from Content c ";
		def args = new HashMap()
		if(m){
			hql += " where c.menu= :menu "
			args.put("menu", m);
		}
		
		if(params.search){
			if(args.size() == 0)
				hql += " where "
			else 
				hql += " and "
			hql += "( c.title like '%" +params.search+ "%' or c.text like '%"+params.search+"%')"
		} 
		
		List<Content> contentList = Content.findAll(hql,args, 
		["max":max,"offset":offset,sort:"createTime",order:"desc"])
		def total = Content.executeQuery("select count(c)  " + hql,args)[0]
		render (view:"search",
			model:["menu":m,"contentList":contentList,
				"offset":offset,"max":max,"total":total])
	}
	
	def findJson(){
		def msg = ["success":true]
		try{
			if(params.id)
				msg["content"] = Content.get(params.id)
			else if(params.menuId) {//单个任务，查找对应的第一个内容
				def c = Content.createCriteria() 
				def m = Menu.get(params.menuId)
				
				def content = c {
					eq("menu",m)
					maxResults(1)
					order("id","asc")
				}
				msg["content"] = content.size() == 0? null : content[0]
			}
		}catch(e){
			e.printStackTrace()
			msg.put("success", false)
			msg.put("msg", e.getMessage())
		}
		render  (contentType:"text/json"){ msg }
	}
	
	def listJson(){
		def msg = ["success":true]
		try{
			def criteria = Content.createCriteria() 
			def max =params.limit? params.limit.toInteger() : 30
			def offset = params.start? params.start.toInteger() : 0
			
			msg["data"] = criteria {
				if(params.menuId)
					eq('menu',Menu.get(params.menuId))
				maxResults(max)
                firstResult(offset)
				order("top","desc")
				order("id","desc")
			}
			msg.limit = max
			msg.start = offset
			msg["total"] = Content.count()
		}catch(e){
			msg.put("success", false)
			msg.put("msg", e.getMessage())
		}
		render  (contentType:"text/json"){ msg }
	}
	
	def save(){
		def msg = ["success":true]
		try{
			def df = new SimpleDateFormat("yyyy-MM-dd")
			Content c = params.id ? Content.load(params.id) : new Content()
			c.source = params.source
			c.author = params.author
			c.createTime =  df.parse(params.createTime)
			c.text = params.text
			c.title = params.title
			c.menu = Menu.load(params.menuId)
			if(!c.validate())
				c.errors.each {
					def errrorMsg = MessageFormat.format(it.fieldError.getDefaultMessage(),it.fieldError.arguments)
					throw new Exception(errrorMsg)
				}
			c.save()
			
			//save fileItems
			params.fileItems.each {
				FileItem fileIt = FileItem.get(it)
				if(fileIt){
					fileIt.content = c
					fileIt.save()
				}
			}
			msg.content = c
		}catch(e){
			msg.put("success", false)
			msg.put("msg", e.getMessage())
		}
		render  (contentType:"text/json"){
			msg
		}
	}
	
	def top(){
		def msg = ["success":true]
		try{
			//删除旧top
			def oldTop = Content.findByTop(1)
			if(oldTop){
				oldTop.each {
					oldTop.top = 0
					oldTop.save()
				}
			}
			//设置新top
			def content = Content.get(params.id)
			if(content){
				content.top = 1
				content.save()
			}
		}catch(e){
			e.printStackTrace()
			msg.put("success", false)
			msg.put("msg", e.getMessage())
		}
		render  (contentType:"text/json"){ msg }
	}
	
	def delete(){
		def msg = ["success":true]
		try{
			def content = Content.get(params.id)
			if(content)
				content.delete()
		}catch(e){
			msg.put("success", false)
			msg.put("msg", e.getMessage())
		}
		render  (contentType:"text/json"){ msg }
	}
	
	def indexImage(){
		def msg = ["success":true]
		try{
		}catch(e){
			msg.put("success", false)
			msg.put("msg", e.getMessage())
		}
	render  (contentType:"text/json"){ msg }
		}
}
